package com.voicenews.activity;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

import com.voicenews.VoiceNewsApplication;
import com.voicenews.R;
import com.voicenews.playtts.ShowExtractedArticle;
import com.voicenews.utils.Utils;
import com.voicenews.webserviceconnect.ICallbackHandler;
import com.voicenews.webserviceconnect.WebServiceConnector;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.Toast;

public class ArticlesListShowActivity extends DashBoardActivity implements
		ICallbackHandler {
	private ListAdapter adapter;
	private String category = null;
	private ListView listView;
	private List<JSONObject> objects = null;
	private boolean reloadFlag = false;
	private Button addNews;
	public static ProgressDialog dialog;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		System.out.println("oncreate");
		setContentView(R.layout.news_list_shows);
		listView = (ListView) findViewById(R.id.article_list);
		category = getIntent().getStringExtra("category");
		setHeader("Tin Tức " + category, true, true, true, false);
		addNews = new Button(this);
		addNews.setText(R.string.addload_menu_item);
		addNews.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				loadArticlesAddition();
			}
		});

		listView.addFooterView(addNews);
		// adapter = this.getListAdapter();
		VoiceNewsApplication.getInstance();
		objects = (List<JSONObject>) VoiceNewsApplication.getAdaptersCache()
				.get(category);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				JSONObject json = (JSONObject) adapter.getItem(arg2);
				try {
					URL url = (URL) json.get("url");
					// Intent browserIntent = new
					// Intent(Intent.ACTION_VIEW,
					// Uri.parse(url.toString()));
					// startActivity(browserIntent);
					Intent i1 = new Intent(getApplicationContext(),
							ArtilceShowActivity.class);
					i1.putExtra("urlString", url.toString());
					i1.putExtra("title", json.get("title").toString());
					i1.putExtra("articleId", json.get("articleId").toString());
					startActivity(i1);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});

		if (objects == null) {
			if (Utils.isNetworkAvailable(this)) {
				VoiceNewsApplication.getInstance();
				VoiceNewsApplication.getOffsetCache().put(category + "offset",
						Integer.valueOf(0));
				loadArticles(category, 0);
				System.out.println("conneting internet");
			} else {
				Toast.makeText(getApplicationContext(), "no internet",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			adapter = new ArticlesListAdapter(this, objects);
			listView.setAdapter(adapter);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	}

	@Override
	public void response(String response) {
		Log.d("callMethod", response);

		if (objects == null || reloadFlag) {
			objects = new ArrayList<JSONObject>();
			reloadFlag = false;
		}

		int previousPosition = objects.size();
		objects.addAll(Utils.convertToJSONObjects(response));
		adapter = new ArticlesListAdapter(this, objects);

		listView.setAdapter(adapter);
		listView.setSelection(previousPosition);

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		VoiceNewsApplication.getInstance();
		VoiceNewsApplication.getAdaptersCache().put(category, objects);
		System.out.println("onpause");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		System.out.println("ondestroy");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.news_list_shows_options, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.reload_menu_item:
			reloadArticles();
			break;
		case R.id.addload_menu_item:
			loadArticlesAddition();
			break;
		default:
			break;
		}

		return true;
	}

	private void reloadArticles() {
		if (Utils.isNetworkAvailable(this)) {
			VoiceNewsApplication.getInstance();
			VoiceNewsApplication.getOffsetCache().put(category + "offset", 0);
			reloadFlag = true;
			loadArticles(category, 0);
		} else {
			Toast.makeText(this, "no internet", Toast.LENGTH_SHORT).show();
		}
	}

	private void loadArticles(String category, int offset) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("category", category);
		params.put("offset", String.valueOf(offset));
		callWebService(params);
	}

	private void loadArticlesAddition() {
		// TODO Auto-generated method stub
		if (Utils.isNetworkAvailable(VoiceNewsApplication.getInstance()
				.getApplicationContext())) {
			VoiceNewsApplication.getInstance();
			Integer offset = VoiceNewsApplication.getOffsetCache().get(
					category + "offset");
			offset += 10;
			VoiceNewsApplication.getInstance();
			VoiceNewsApplication.getOffsetCache().put(category + "offset",
					offset);
			loadArticles(category, offset);
		} else {
			Toast.makeText(
					VoiceNewsApplication.getInstance().getApplicationContext(),
					"no internet", Toast.LENGTH_SHORT).show();
		}
	}

	private void callWebService(Map<String, String> params) {
		WebServiceConnector webServiceConnector = new WebServiceConnector(
				VoiceNewsApplication.hostService + "rest/services/",
				"articles", params, this, WebServiceConnector.GET_METHOD, this);
		webServiceConnector.execute();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		System.out.println("onrestart");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("onresume");
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println("onstart");

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		System.out.println("onstop");
	}

	@Override
	public void btnRefreshClick(View v) {
		// TODO Auto-generated method stub
		if (Utils.isNetworkAvailable(this)) {
			VoiceNewsApplication.getInstance();
			VoiceNewsApplication.getOffsetCache().put(category + "offset", 0);
			reloadFlag = true;
			loadArticles(category, 0);
		} else {
			Toast.makeText(this, "no internet", Toast.LENGTH_SHORT).show();
		}
	}

}
